/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++){
            map.put(inorder[i], i);
        }
        int n = preorder.length;

        return build(preorder, 0, n-1, 0, n-1, map);
    }

    private TreeNode build(int[] preorder, int preStart, int preEnd, int inStart, int inEnd, Map<Integer, Integer> map){
        if (preStart > preEnd) return null;
        
        TreeNode node = new TreeNode(preorder[preStart]);

        int rootIndex = map.get(node.val); 

        node.left = build(preorder, preStart+1, preStart+rootIndex-inStart, inStart, rootIndex-1, map);
        node.right = build(preorder, preStart+rootIndex-inStart+1, preEnd, rootIndex+1, inEnd, map);

        return node;
    }
}